package org.ilovecode.display {
	import flash.display.MovieClip;
	import flash.display.Sprite;
	
	/**
	 * ...
	 * @author Vjekoslav Ratkajec
	 */
	public class BoundContainer extends MovieClip {
		
		private const BOUND_OFFSET:uint = 10;
		private var content:Sprite = null;
		private var position:String = "BR";
		
		public function BoundContainer(width:Number, height:Number, position:String) {
			//Validate parameters
			//First letter - row: Top, Center, Bottom
			//Second letter - column: Left, Center, Right
			var availablePositions:Array = new Array("TL", "TC", "TR", "CL", "CC", "CR", "BL", "BC", "BR");
			if (width <= 0 || height <= 0 || availablePositions.indexOf(position) == -1) {
				throw new VerifyError("Illegal parameters");
			}
			
			this.position = position;
			
			//Draw opaque box to set height and width of container
			var boundingBox:Sprite = new Sprite();
			boundingBox.graphics.beginFill(0, 0);
			boundingBox.graphics.drawRect(0, 0, width, height);
			boundingBox.graphics.endFill();
			this.addChild(boundingBox);
		}
		
		public function setContent(content:Sprite):void {
			//Clear container
			while (this.numChildren > 1) this.removeChildAt(1);
			
			this.content = content;
			doResize();
			doPosition();
			this.addChild(this.content);
		}
		
		private function doResize():void {
			if (content.width > this.width || content.height > this.height) {
				var xratio:Number = (this.width - BOUND_OFFSET) / content.width;
				var yratio:Number = (this.height - BOUND_OFFSET) / content.height;
				var ratio:Number = (xratio < yratio) ? xratio : yratio;
				
				content.scaleX = ratio;
				content.scaleY = ratio;
			}
		}
		
		private function doPosition():void {
			switch (position) {
				case "TL":
					content.x = 0;
					content.y = 0;
					break;
				case "TC":
					content.x = (this.width - content.width) / 2;
					content.y = 0;
					break;
				case "TR":
					content.x = (this.width - content.width);
					content.y = 0;
					break;
				case "CL":
					content.x = 0;
					content.y = (this.height - content.height) / 2;
					break;
				case "CC":
					content.x = (this.width - content.width) / 2;
					content.y = (this.height - content.height) / 2;
					break;
				case "CR":
					content.x = (this.width - content.width);
					content.y = (this.height - content.height) / 2;
					break;
				case "BL":
					content.x = 0;
					content.y = (this.height - content.height);
					break;
				case "BC":
					content.x = (this.width - content.width) / 2;
					content.y = (this.height - content.height);
					break;
				case "BR":
					content.x = (this.width - content.width);
					content.y = (this.height - content.height);
					break;
				default:
					throw new VerifyError("Illegal position");
			}
			
		}
		
		public function getContent():Sprite {
			return content;
		}
		
	}

}